<template>
  <view class="map-popup" v-if="visible" @touchmove.stop.prevent="() => {}">
    <view class="popup-mask" @click="closePopup"></view>
    <view class="popup-content">
      <view class="popup-header">
        <text class="header-title">设备位置</text>
        <text class="close-btn" @click="closePopup">×</text>
      </view>
      <map
        class="map-container"
        :longitude="props.longitude"
        :latitude="props.latitude"
        :markers="markers"
        :scale="16"
      ></map>
      <view @click="navigateToLocation" class="navigate-button" >
        <text>导航</text>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, watch } from "vue";

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  longitude: {
    type: Number,
    default: 0,
  },
  latitude: {
    type: Number,
    default: 0,
  },
  title: {
    type: String,
    default: "设备位置",
  },
  address: {
    type: String,
    default: "",
  },
});

const emit = defineEmits(["close"]);

interface Marker {
  id: number;
  longitude: number;
  latitude: number;
  title: string;
  width: number;
  height: number;
}

const markers = ref<Marker[]>([]);

// 监听经纬度变化，更新标记点
watch([() => props.longitude, () => props.latitude], ([newLon, newLat]) => {
  if (newLon && newLat) {
    markers.value = [
      {
        id: 1,
        longitude: newLon,
        latitude: newLat,
        title: "设备位置",
        width: 30,
        height: 30,
      },
    ];
  }
});
const navigateToLocation = () => {
  // 确保经纬度有效
  if (props.latitude && props.longitude) {
    wx.openLocation({
      latitude: props.latitude,
      longitude: props.longitude,
      // 传入名称和地址能提供更好的体验
      name: props.title,
      address: props.address,
      scale: 18 // 可选缩放级别
    });
  } else {
    console.warn('Invalid latitude or longitude for navigation.');
    // 可以添加一个提示给用户
  }
};

const closePopup = () => {
  emit("close");
};
</script>

<style scoped lang="scss">
.map-popup {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 999;
  display: flex;
  align-items: flex-end;
}
.navigate-button {
  padding: 20rpx;
  text-align: center;
  background-color: #007aff; // 可根据主题调整
  color: white;
  font-size: 32rpx;
  margin: 20rpx;
  border-radius: 10rpx;
}
.popup-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
}

.popup-content {
  width: 100%;
  background-color: #fff;
  border-top-left-radius: 20rpx;
  border-top-right-radius: 20rpx;
  overflow: hidden;
  transform: translateY(0);
  transition: transform 0.3s ease;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  background-color: #f8f8f8;
}

.header-title {
  font-size: 32rpx;
  font-weight: bold;
}

.close-btn {
  font-size: 40rpx;
  color: #999;
  padding: 10rpx;
}

.map-container {
  width: 100%;
  height: 1000rpx;
}
</style>